<template>
  <div class="admins">
    <el-card>
      <div slot="header">
        <span>管理员管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showAddDialog">
          <i class="el-icon-plus"></i> 新增管理员
        </el-button>
      </div>
      
      <!-- 搜索栏 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名/邮箱"
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchRole" placeholder="选择角色" clearable>
            <el-option label="超级管理员" value="super"></el-option>
            <el-option label="普通管理员" value="admin"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchStatus" placeholder="选择状态" clearable>
            <el-option label="启用" value="active"></el-option>
            <el-option label="禁用" value="inactive"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>

      <!-- 管理员列表 -->
      <el-table :data="filteredAdmins" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">{{ getRoleText(scope.row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissions" label="权限" width="200">
          <template slot-scope="scope">
            <el-tag 
              v-for="perm in scope.row.permissions" 
              :key="perm" 
              size="mini" 
              style="margin-right: 5px;"
            >
              {{ getPermissionText(perm) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'active' ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="mini" type="warning" @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑管理员对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminForm.username" placeholder="请输入用户名" :disabled="!!adminForm.id"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!adminForm.id">
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="adminForm.role">
            <el-radio value="super">超级管理员</el-radio>
            <el-radio value="admin">普通管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="adminForm.permissions">
            <el-checkbox label="question_manage">题目管理</el-checkbox>
            <el-checkbox label="category_manage">分类管理</el-checkbox>
            <el-checkbox label="user_manage">用户管理</el-checkbox>
            <el-checkbox label="admin_manage">管理员管理</el-checkbox>
            <el-checkbox label="analytics_view">数据分析</el-checkbox>
            <el-checkbox label="system_setting">系统设置</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="adminForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="adminForm.remark"
            placeholder="请输入备注"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" :visible.sync="resetPasswordDialogVisible" width="400px">
      <el-form :model="resetPasswordForm" :rules="resetPasswordRules" ref="resetPasswordForm" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleResetPasswordSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminsManage',
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetPasswordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      searchKeyword: '',
      searchRole: '',
      searchStatus: '',
      admins: [
        {
          id: 1,
          username: 'admin',
          email: 'admin@example.com',
          role: 'super',
          permissions: ['question_manage', 'category_manage', 'user_manage', 'admin_manage', 'analytics_view', 'system_setting'],
          lastLoginTime: '2024-01-15 10:30:00',
          status: 'active',
          createTime: '2023-01-01 00:00:00',
          remark: '超级管理员'
        },
        {
          id: 2,
          username: 'teacher1',
          email: 'teacher1@example.com',
          role: 'admin',
          permissions: ['question_manage', 'category_manage', 'analytics_view'],
          lastLoginTime: '2024-01-14 15:20:00',
          status: 'active',
          createTime: '2023-06-01 09:00:00',
          remark: '题目管理老师'
        },
        {
          id: 3,
          username: 'teacher2',
          email: 'teacher2@example.com',
          role: 'admin',
          permissions: ['user_manage', 'analytics_view'],
          lastLoginTime: '2024-01-13 14:15:00',
          status: 'inactive',
          createTime: '2023-08-15 16:30:00',
          remark: '用户管理老师'
        }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增管理员',
      adminForm: {
        id: null,
        username: '',
        email: '',
        password: '',
        role: 'admin',
        permissions: [],
        status: 'active',
        remark: ''
      },
      adminRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        permissions: [
          { required: true, message: '请选择权限', trigger: 'change' }
        ]
      },
      resetPasswordDialogVisible: false,
      resetPasswordForm: {
        adminId: null,
        newPassword: '',
        confirmPassword: ''
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    filteredAdmins() {
      let result = this.admins;
      
      if (this.searchKeyword) {
        result = result.filter(a => 
          a.username.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          a.email.toLowerCase().includes(this.searchKeyword.toLowerCase())
        );
      }
      
      if (this.searchRole) {
        result = result.filter(a => a.role === this.searchRole);
      }
      
      if (this.searchStatus) {
        result = result.filter(a => a.status === this.searchStatus);
      }
      
      return result;
    }
  },
  watch: {
    filteredAdmins: {
      handler(newVal) {
        this.total = newVal.length;
      },
      immediate: true
    }
  },
  methods: {
    getRoleTagType(role) {
      const roleMap = {
        super: 'danger',
        admin: 'warning'
      };
      return roleMap[role] || 'info';
    },
    getRoleText(role) {
      const roleMap = {
        super: '超级管理员',
        admin: '普通管理员'
      };
      return roleMap[role] || role;
    },
    getPermissionText(permission) {
      const permissionMap = {
        question_manage: '题目管理',
        category_manage: '分类管理',
        user_manage: '用户管理',
        admin_manage: '管理员管理',
        analytics_view: '数据分析',
        system_setting: '系统设置'
      };
      return permissionMap[permission] || permission;
    },
    handleSearch() {
      // 搜索逻辑已在 computed 中处理
    },
    resetSearch() {
      this.searchKeyword = '';
      this.searchRole = '';
      this.searchStatus = '';
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    showAddDialog() {
      this.dialogTitle = '新增管理员';
      this.adminForm = {
        id: null,
        username: '',
        email: '',
        password: '',
        role: 'admin',
        permissions: [],
        status: 'active',
        remark: ''
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑管理员';
      this.adminForm = { ...row };
      this.dialogVisible = true;
    },
    handleToggleStatus(row) {
      const action = row.status === 'active' ? '禁用' : '启用';
      this.$confirm(`确定要${action}这个管理员吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用API
        row.status = row.status === 'active' ? 'inactive' : 'active';
        this.$message.success(`${action}成功`);
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    handleResetPassword(row) {
      this.resetPasswordForm = {
        adminId: row.id,
        newPassword: '',
        confirmPassword: ''
      };
      this.resetPasswordDialogVisible = true;
    },
    handleSubmit() {
      this.$refs.adminForm.validate((valid) => {
        if (valid) {
          // 这里应该调用保存API
          this.$message.success(this.adminForm.id ? '更新成功' : '添加成功');
          this.dialogVisible = false;
          this.loadAdmins();
        }
      });
    },
    handleResetPasswordSubmit() {
      this.$refs.resetPasswordForm.validate((valid) => {
        if (valid) {
          // 这里应该调用重置密码API
          this.$message.success('密码重置成功');
          this.resetPasswordDialogVisible = false;
        }
      });
    },
    loadAdmins() {
      // 这里应该调用获取管理员列表API
      console.log('加载管理员列表');
    }
  }
}
</script>

<style scoped>
.admins {
  padding: 20px;
}
</style>
